<?php
/**
 * 消息订阅者
 * http方式
 */

namespace TigrisMQ;

class HttpConsumer
{
    private $topic;
    private $url;
    private $accessKey;
    private $app_id;

    public function __construct($config)
    {
        $this->topic = isset($config['Topic']) ? $config['Topic'] : '';
        $this->url = isset($config['URL']) ? $config['URL'] : '';
        $this->accessKey = isset($config['AccessKey']) ? $config['AccessKey'] : '';
        $this->app_id = isset($config['app_id']) ? $config['app_id'] : '';
    }

    /**
     * 获取消息
     * @param int $limit 一次请求数据量（1-32）
     * @param int $timeout 确认消费的超时时间（超时后重新回到队列）
     * @return array
     */
    public function getQueueMessages($limit = 1, $timeout = 1800)
    {
        $parameters = [
            'topic' => $this->topic,
            'timeout' => $timeout,
            'limit' => $limit
        ];
        $result = Util::doRequest($this->url, 'GET', '/message/get/', $this->app_id, $this->accessKey, $parameters);
        if (!isset($result['resultNum']) || $result['resultNum'] != 200) {
            return $result;
        }
        foreach ($result['resultData'] as &$item) {
            $itemValue = json_decode($item['object'], true);
            if (is_null($itemValue)) {
                $itemValue = unserialize($item['object']);
            }
            $item['object'] = $itemValue;
        }
        unset($item);
        return $result['resultData'];
    }

    /**
     * 删除消息, 传递单个message
     * @param array $message 通过getQueueMessages获取的单个消息
     * @return array
     */
    public function deleteQueueMessage($message)
    {
        if (!isset($message['token'])) {
            return 'token不能为空';
        }
        $parameters = [
            'topic' => $this->topic,
            'token' => $message['token']
        ];
        return Util::doRequest($this->url, 'POST', '/message/delete/', $this->app_id, $this->accessKey, $parameters);
    }
}
